Lesson 4 - newbie exercise
For each scenario suggested below create the corresponding set of if statments. If you are finding it difficult you should create a truth tree diagram.
balance = 200
def withdrawCash(amount):
# will only allow cash to be deducted if there is enough balance
# if there is not enough cash then it will say "not enough money in account"
withdrawCash(100)
withdrawCash(80)
withdrawCash(60) # should print here
Suggested change- Add the if statement as suggested by the comments.
balance = 200
def withdrawCash(amount):
# will only allow cash to be deducted if there is enough balance
# if there is not enough cash then it will say "not enough money in account"
if balance - amount < 0:
print "not enough money in account"
else:
balance = balance - amount
withdrawCash(100)
withdrawCash(80)
withdrawCash(60) # should print here
Toggle answer
balance = 200
hasOverdraft = True
def withdrawCash(amount):
# if they have a overdraft then they can go to -200
withdrawCash(120)
withdrawCash(250)
withdrawCash(80) # should print a message
Suggested change - You should change your answer to the last question in order to get the solution.
balance = 200
hasOverdraft = True
def withdrawCash(amount):
# if they have a overdraft then they can go to -200
if balance - amount < 0:
if hasOverdraft and balance - amount > -200:
balance = balance - amount
else:
print "not enough money in account"
else:
balance = balance - amount
# or...
def withdrawCash(amount):
if hasOverdraft:
if balance - amount < -200:
print "not enough money in account"
else:
alance = balance - amount
else:
if balance - amount < 0:
print "not enough money in account"
else:
balance = balance - amount
withdrawCash(120)
withdrawCash(250)
withdrawCash(80) # should print a message
Toggle answer
def min(z,y):
if z < y: return z
else: return y
Suggested changes - Change the code so it will find the smallest of 3 numbers
def min(z,y,x):
if z < y:
if z < x: return z
else: return x
else:
if y < x: return y
else: return x
Toggle answer